package org.xjc.config.securitycomponent;


import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.xjc.entity.MenuEntity;
import org.xjc.entity.RoleEntity;
import org.xjc.service.SecurityMenuService;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @Author : XJC
 * @Time : 2021/12/27 19:22
 * @Description :权限控制，根据请求url分析需要的角色，拒绝与用户role权限不匹配的请求
 */
public class CustomSecurityMetadataSourceFilter implements FilterInvocationSecurityMetadataSource {

    @Resource
    private SecurityMenuService menuService;


    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        //获取请求的url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<MenuEntity> menuEntities = menuService.getAllMenusWithRoles();
        for (MenuEntity menuEntity : menuEntities) {
//            判断请求url与数据库的url相匹配，如果匹配就返回需要的role
            if (!StringUtils.isBlank(menuEntity.getUrl())&&antPathMatcher.match(menuEntity.getUrl(),requestUrl)){
                String[] str = menuEntity.getRoles().stream().map(RoleEntity::getRoleCode).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        //没匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
